package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.results.Code;
import com.itheima.controller.results.Result;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")//公共映射路径
public class UserController {

    @Autowired
    private UserService userService;

    //localhost:8081/user/?userName=Jock&password=1234&realName=JockMe&gender=1&birthday=1999/09/09
    @PostMapping
    public Result save(User user){
        boolean flag = userService.save(user);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERROR);
    }

    //localhost:8081/user/?userName=Jock&password=1234&realName=JockMe&gender=1&birthday=1999/09/09
    @PutMapping
    public Result update(User user){
        boolean flag = userService.update(user);
        return new Result(flag? Code.UPDATE_OK: Code.UPDATE_ERROR);
    }

    //localhost:8081/user/4
    @DeleteMapping("/{uuid}")
    public Result delete(@PathVariable Integer uuid){
        boolean flag = userService.delete(uuid);

        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERROR);
    }

    //localhost:8081/user/1
    @GetMapping("/{uuid}")
    public Result getById(@PathVariable Integer uuid){//@PathVariable用来获取页面传过来的值
        User user = userService.getById(uuid);
        if (uuid == 10) throw new BusinessException("查询出错了，请重试",Code.GET_OK);
        return new Result(user != null? Code.GET_OK:Code.DELETE_ERROR,user);
    }

    //localhost:8081/user/1/2
    @GetMapping("/{page}/{size}")
    public Result getAll(@PathVariable Integer page,@PathVariable Integer size){
        PageInfo<User> all = userService.getAll(page, size);
        return new Result(all != null ? Code.GET_OK:Code.GET_ERROR,all);

    }

    //localhost:8081/user/login?userName=Jock123321&password=1234
    @PostMapping("/login")
    public Result login(String userName,String password){
        //返回的对象是User类，所以一般变量名就是类的小写字母开头
        User user = userService.login(userName, password);
        return new Result(user != null ? Code.GET_OK:Code.GET_ERROR,user);
    }
}
